package com.cac.demo.controller.materialReceive;

import com.cac.demo.dao.msWorkbinMaterial.MsWorkbinMaterialDao;
import com.cac.demo.entity.msWorkbinMaterial.MsWorkbinMaterialDTO;
import com.cac.demo.service.MsSslShelves.MsSslShelvesService;
import com.cac.demo.service.materialReceive.MaterialReceiptService;
import com.cac.demo.service.outStoreRoom.OutStoreroomService;
import com.cac.demo.service.tsUSer.tsUserImpl.TsUserServiceImpl;
import com.cac.demo.util.CreateCommonLog;
import com.cac.demo.entity.materialScan.WmsDeliverPlanDTO;
import com.cac.demo.dao.materialReceive.WmsItemInventoryDao;
import com.cac.demo.util.MaterialReceiptUtil;
import com.cac.demo.dao.gkLog.MsGkLogDao;
import com.cac.demo.controller.msSslShelves.MsSslShelvesRest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import com.cac.demo.util.adapter.ResponseMsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @program test-curd
 * @description 物料入库接口
 * @author: LSL
 * @create: 2022-08-27-16-00
 **/
@Slf4j
@RestController
@RequestMapping("/materialReceipt")
public class MaterialReceiptRest {
    @Autowired
    private MaterialReceiptService materialReceiptService;
    @Autowired
    private MsSslShelvesService msSslShelvesService;
    @Autowired
    private MsWorkbinMaterialDao msWorkbinMaterialDao;
    @Autowired
    private WmsItemInventoryDao wmsItemInventoryDao;
    @Autowired
    private MaterialReceiptUtil materialReceiptUtil;
    @Autowired
    private MsSslShelvesRest msSslShelvesRest;
    @Autowired
    private CreateCommonLog createCommonLog;
    @Autowired
    private MsGkLogDao msGkLogDao;
    @Autowired
    private TsUserServiceImpl tsUserService;
    @Autowired
    private OutStoreroomService outStoreroomService;
    @Autowired
    private Environment environment;

    /**
     * 根据WmsDeliverPlanDTO 实体内容插入入库申请单主表接口
     * 条码，对应的物料箱条码，每一个条码对应的数量
     * 状态修改为已接收入库
     *
     * @param map
     * @return
     */
    @PostMapping("/materialReceipt")
    public ResponseMsg<String> materialReceipt(@RequestBody HashMap map) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        //缓存箱编码
        String workbinCode = map.get("workbinCode").toString();
        //获取操作人信息
        String departid = map.get("departid").toString();
        String account = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(account)) {
            log.info("session过期，请重新登陆");
            responseMsg.setErrorDesc("账户已过期，请重新登录").setRetCode("201");
            return responseMsg;
        } else if ("admin".equals(account)) {
            return responseMsg.setRetCode("201").setErrorDesc("管理员账号无法完成操作，请切换登录用户");
        }
        log.info("account+++++++++" + account);
        JSONObject json = new JSONObject();
        //待入库数据集合
        List<WmsDeliverPlanDTO> planDTOs = (List<WmsDeliverPlanDTO>) map.get("planDTOs");
        if (planDTOs == null || planDTOs.size() == 0) {
            return responseMsg.setRetCode("201").setMessage("物料入库失败");
        }
        String shop = (String) tsUserService.getUserInfoByAccount(account).get("shop");
        responseMsg = materialReceiptService.materialReceipt(planDTOs, workbinCode, departid, account, IP, shop);
        if (responseMsg.getRetCode().equals("200")) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("入库成功！");
        } else {
            responseMsg.setRetCode("201");
            responseMsg.setErrorDesc(responseMsg.getMessage());
        }
//        //是否现场退库物料
//        String statu = materialReceiptService.searchPlanRet(planDTOs);
//        if (statu != null && statu.equals("2")) {//待添加备注
//            responseMsg = materialReceiptService.updateWmsItemInventory(planDTOs, workbinCode, account, IP);
//            if (responseMsg.getRetCode().equals("200")) {
//                responseMsg.setRetCode("200");
//                responseMsg.setMessage("入库成功！");
//            } else {
//                responseMsg.setRetCode("201");
//                responseMsg.setMessage(responseMsg.getMessage());
//            }
//        }
//        if (statu != null && statu.equals("201")) {
//            if (responseMsg.getRetCode().equals("200")) {
//                responseMsg.setRetCode("200");
//                responseMsg.setMessage("入库成功！");
//            } else {
//                responseMsg.setRetCode("201");
//                responseMsg.setMessage(responseMsg.getMessage());
//            }
//        }
//        if (statu == null) {//物料首次入库
//            String shop = (String) tsUserService.getUserInfoByAccount(account).get("shop");
//            responseMsg = materialReceiptService.materialReceipt(planDTOs, workbinCode, departid, account, IP, shop);
//            if (responseMsg.getRetCode().equals("200")) {
//                responseMsg.setRetCode("200");
//                responseMsg.setMessage("入库成功！");
//            } else {
//                responseMsg.setRetCode("201");
//                responseMsg.setErrorDesc(responseMsg.getMessage());
//            }
//        }
        /*try {
            // 延时10秒
            Thread.sleep(25000);
            System.out.println("延时结束");
            return responseMsg;
        } catch (InterruptedException e) {
            // 如果线程被中断，这里会捕获到InterruptedException
            e.printStackTrace();
            return responseMsg;
        }*/
        return responseMsg;
    }

    /**
     * 交接单回退 由状态为3回退到2
     * 针对已经叫了箱，还要回退的这种情况
     */
    @PostMapping("backDeliverys")
    public ResponseMsg backDeliverys(@RequestBody List<HashMap> deliverys) {
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        return materialReceiptService.backDevlieryToReceive(deliverys, IP);
    }

    /**
     * -------------------------------------------------------
     * 物料入库叫箱接口
     * -------------------------------------------------------
     */
    @PostMapping("/materialReceiptCallCase")
    public synchronized ResponseMsg<String> materialReceiptCallCase(@RequestBody Map map) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        List<HashMap<String, Object>> sqlRetrun = materialReceiptService.materialReceiptCallCase(map);
        //叫缓存箱成功集合
        List<String> succWorkbin = new ArrayList<>();
        //缓存箱叫出失败
        List<String> failWorkbin = new ArrayList<>();
        //成功叫箱货位
        List<String> succShelvesCode = new ArrayList<>();
        //成功数量
        Integer succWorkbinCount = 0;
        //失败数量
        Integer failWorkbinCount = 0;
        for (HashMap<String, Object> result : sqlRetrun
        ) {
            /**
             * palletCode 缓存箱编码
             * startCode 开始位置，叫箱开始位置为箱子所在立体库货架位置
             * roadway  缓存箱所在巷道
             * endCode  结束位置，发起任务所在位置
             */
            String palletCode = result.get("WORKBIN_CODE").toString();
            String startCode = result.get("SHELVES_CODE").toString();
            String roadway = result.get("ROW_NO").toString();
            System.out.println(startCode + "----------------------------");
            //当前设想，根据操作位IP地址查询数据库操作位字典，得到操作位id如1167
            String endCode = "1167";
            /**
             * 此处需要先判断开始位置是否为双伸位，若在双伸位，需要调用检查储位功能判断开始位置是否有阻挡，
             * 若有阻挡，需要再出库操作之前，先进项移库操作。
             * 功能暂未开发=------------
             */
            //设置调用wcs接口，下发出库任务
            Integer uuid = UUID.randomUUID().toString().hashCode();
            uuid = uuid < 0 ? -uuid : uuid;
            Long wmsTaskId = Long.valueOf(uuid);
            HashMap<String, Object> parameter = new HashMap<>();
            parameter.put("command", "1");
            parameter.put("taskType", "2");
            parameter.put("wmsTaskId", wmsTaskId);
            parameter.put("roadway", roadway);
            parameter.put("palletCode", palletCode);
            parameter.put("startCode", startCode);
            parameter.put("endCode", endCode);
            String callReturn = msSslShelvesService.doTask(parameter);
            Map<String, Object> jsonMap = JSON.parseObject(callReturn, new TypeReference<HashMap<String, Object>>() {
            });
            if (jsonMap.get("code").equals("200")) {
                succWorkbin.add(palletCode);
                succShelvesCode.add(startCode);
                succWorkbinCount++;
            } else {
                failWorkbin.add(palletCode);
                failWorkbinCount++;
            }
        }
        //根据叫出的缓存箱编码，维护立体库数据库信息，叫出的缓存箱对应库位解除绑定
        msSslShelvesService.updateSslShelvesByShelvesCode(succShelvesCode);
        responseMsg.setRetCode("200");
        responseMsg.setMessage("成功叫出" + succWorkbinCount + "个缓存箱；物料箱编码为：" + succWorkbin.toString() +
                "失败叫箱数量为：" + failWorkbinCount + "失败物料箱编码为：" + failWorkbin.toString());
        return responseMsg;
    }

    /**
     *
     */


//    /**
//     * 根据物料箱编码，查询该物料箱中具体物料信息
//     * @param map
//     * @return
//     */
//    @PostMapping("/searchWorkbinMaterial")
//    public ResponseMsg<List<MsWorkbinMaterialDTO>>searchWorkbinMaterial(@RequestBody Map map){
//        String workbinCode = map.get("workbinCode").toString();
//        ResponseMsg<List<MsWorkbinMaterialDTO>> responseMsg = new ResponseMsg<>();
//        responseMsg.setResponseBody(materialReceiptService.searchWorkbinMaterial(workbinCode));
//        return responseMsg;
//    }


    /**
     * 根据扫描的物料箱编码，获取该物料待入库物料信息
     *
     * @param map
     * @return
     */
    @PostMapping("/searchAwaitStorage")
    public ResponseMsg<List<HashMap>> searchAwaitStorage(@RequestBody Map map) {
        ResponseMsg<List<HashMap>> responseMsg = new ResponseMsg<>();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String account = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(account)) {
            log.info("session过期，请重新登陆");
            responseMsg.setMessage("账户已过期，请重新登录").setRetCode("201");
            return responseMsg;
        } else if ("admin".equals(account)) {
            return responseMsg.setRetCode("201").setErrorDesc("管理员账号无法完成操作，请切换登录用户");
        }
        String workbinCode = (String) map.get("workbinCode");
        List<HashMap> list = materialReceiptService.searchAwaitStorage(workbinCode, IP);

        log.info("长度"+list.size());
        if (list == null || list.size() == 0) {
            return responseMsg.setRetCode("201").setMessage("缓存箱编码不存在!");
        }
        responseMsg.setResponseBody(list);
        return responseMsg;
    }

    //物料入库扫码时返回大件货物库位号
    @PostMapping("/searchLocatorNo")
    public ResponseMsg<List<HashMap>> searchLocatorNo() {
        ResponseMsg<List<HashMap>> responseMsg = new ResponseMsg<>();
        List<HashMap> map = materialReceiptService.searchLocatorNo();
        if (map == null || map.size() == 0) {
            responseMsg.setRetCode("200").setMessage("没有数据");
        } else {
            responseMsg.setRetCode("200").setResponseBody(map);
        }
        return responseMsg;
    }

    /**
     * 根据缓存箱编码，查询缓存箱中存放的物料信息 v2.0
     *
     * @param map
     * @return
     */
    @PostMapping("/searchInventoryMaterial")
    public ResponseMsg<List<HashMap>> searchInventoryMaterial(@RequestBody Map map) {
        ResponseMsg<List<HashMap>> responseMsg = new ResponseMsg<>();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String opUserCode = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(opUserCode)) {
            return responseMsg.setMessage("登录过期，请重新登录").setRetCode("201");
        }
        map.put("ip", IP);
        List<HashMap> list = materialReceiptService.searchInventoryMaterial(map);

        if (list.size() >= 1) {
            responseMsg.setResponseBody(list).setRetCode("200");
        } else {
            responseMsg.setRetCode("201").setMessage("缓存箱分拣信息为空，请检查箱子是否在分拣位或者工作包信息是否正确！");
        }
        return responseMsg;
    }

//    /**
//     * 分拣物料到工作包
//     * @param map
//     * @return
//     */
//    @PostMapping("/putToolPackage")
//    public ResponseMsg<List<MsAoMatchInfoDTO>> putToolPackage(@RequestBody  Map map){
//        ResponseMsg<List<MsAoMatchInfoDTO>> responseMsg = new ResponseMsg<>();
//        String toolCode = (String) map.get("toolCode");
//        List<MsAoMatchInfoDTO> materialDTOs = (List<MsAoMatchInfoDTO>) map.get("materialDTOs");
//            String result = materialReceiptService.putToolPackage(toolCode,materialDTOs);
//            if (result.equals("200")){
//                responseMsg.setRetCode("200");
//                responseMsg.setMessage("操作成功！");
//            }else {
//                responseMsg.setRetCode("201");
//                responseMsg.setErrorDesc(result);
//            }
//        return responseMsg;
//    }

    /**
     * 分拣物料到工作包 -V2.0
     *
     * @param map
     * @return
     */
    @PostMapping("/putToolPackage")
    public ResponseMsg<HashMap> putToolPackage(@RequestBody Map map) {
        ResponseMsg<HashMap> responseMsg = new ResponseMsg<>();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String opUserCode = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(opUserCode)) {
            return responseMsg.setMessage("登录过期，请重新登录").setRetCode("201");
        }
        String toolCode = (String) map.get("toolCode");
        List<HashMap> materialDTOs = (List<HashMap>) map.get("materialDTOs");

        log.info("参数：" + materialDTOs.toString());
        //校验1.分拣数量不能大于配套数量2.分拣数量不能大于库存剩余数量
        for (HashMap check : materialDTOs) {
            int outqty = Integer.parseInt(check.get("outQty").toString());
            int matchQty = Integer.parseInt(check.get("matchQty").toString());
            int currentQty = wmsItemInventoryDao.searchCurrentQty(check.get("wmsItemInventoryId").toString());
            if (outqty > matchQty) {
                return responseMsg.setMessage(check.get("itemCode").toString() + "图号："
                        + check.get("qualityCode").toString() + "质编，分拣数量大于了配套数量，请确认!").setRetCode("201");
            } else if (outqty > currentQty) {
                return responseMsg.setMessage(check.get("itemCode").toString() + "图号："
                        + check.get("qualityCode").toString() + "质编，分拣数量大于了库存剩余数量，请确认!").setRetCode("201");
            }
        }

        //yebo 新增分拣校验物料是否分拣数量大于需求数量
        HashMap<String, Integer> cMap = new HashMap<String, Integer>();
        for (HashMap tp : materialDTOs) {
            if (!cMap.containsKey(tp.get("msAoMatchBillId"))) {
                cMap.put(tp.get("msAoMatchBillId").toString(), Integer.parseInt(tp.get("outQty").toString()));
            } else {
                cMap.put(tp.get("msAoMatchBillId").toString(), cMap.get(tp.get("msAoMatchBillId")) + Integer.parseInt(tp.get("outQty").toString()));
            }
        }
        for (Map.Entry<String, Integer> entry : cMap.entrySet()) {
            HashMap re = msWorkbinMaterialDao.checkPackageNumIsError(entry.getKey(), entry.getValue());
            if ("Y".equals(re.get("checkError"))) {
                return responseMsg.setMessage(re.get("itemCode").toString() + "图号分拣数量大于了需求数量，请确认!").setRetCode("201");
            }
        }

        HashMap result = materialReceiptService.putToolPackage(toolCode, materialDTOs, opUserCode, IP);
        if (result.get("retCode").equals("200")) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("操作成功！" + result.get("msg"));
        } else {
            responseMsg.setRetCode("201");
            responseMsg.setErrorDesc(result.get("msg").toString());
        }
        return responseMsg;
    }

    /**
     * 根据工作包编码查询工作包中数据信息
     *
     * @param map
     * @return
     */
    @PostMapping("/searchToolMaterial")
    public ResponseMsg<HashMap> searchToolMaterial(@RequestBody Map map) {
        ResponseMsg<HashMap> responseMsg = new ResponseMsg<>();
        String toolCode = (String) map.get("toolCode");
        String func = (String) map.get("func");
        if (toolCode.equals("")) {
            return responseMsg.setMessage("请输入工作包条码！").setRetCode("201");
        }
        //yebo 新增校验判断是否需要扫下一个工作包
      /*  responseMsg = msTaskCheckOperService.checkTPTaskIsFinal("package",toolCode);
        if("201".equals(responseMsg.getRetCode())){
            return responseMsg;
        }
        msTaskCheckOperService.insertConsoleOperLog(toolCode);*/
        HashMap material = new HashMap();
        List<MsWorkbinMaterialDTO> list = materialReceiptService.searchToolMaterial(toolCode, func);
        material.put("originalMaterial", list);
        return responseMsg;
    }


    /**
     * ------------------------------------------------------
     * 工艺更改分拣页面接口
     * ------------------------------------------------------
     */

    /**
     * 工艺更改分拣保存接口
     *
     * @param map
     * @return
     */
    @PostMapping("/changeSorting")
    public ResponseMsg<String> changeSorting(@RequestBody HashMap map) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String result = materialReceiptService.changeSorting(map);
        if (result.equals("200")) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("分拣成功！");
        } else {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("分拣失败！");
            responseMsg.setErrorDesc(result);
        }
        return responseMsg;
    }
    /**
     * ------------------------------------------------------
     * end
     * ------------------------------------------------------
     */

    /**
     * ------------------------------------------------------
     * 工作包料箱拆包接口
     * ------------------------------------------------------
     */
    @PostMapping("/toolKitUnpacking")
    public ResponseMsg<HashMap> toolKitUnpacking(@RequestBody Map map) {
        ResponseMsg<HashMap> responseMsg = new ResponseMsg<>();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String opUserCode = (String) request.getSession().getAttribute("account");
        map.put("IP", IP);
        map.put("opUserCode", opUserCode);
        HashMap result = materialReceiptService.toolKitUnpacking(map);
        if (result.get("retCode").equals("200")) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("拆包成功！");
        } else {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("拆包失败！");
        }
        return responseMsg;
    }

    @PostMapping("/callToolUnpack")
    public ResponseMsg<HashMap> callToolUnpack(@RequestBody HashMap map) {
        ResponseMsg<HashMap> responseMsg = new ResponseMsg<>();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        map.put("IP", IP);
        List list = (List) map.get("unpackInfoList");
        if (list == null || list.size() == 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("当前没有需要拆包的任务");
            return responseMsg;
        }
        //调用
        HashMap result = materialReceiptService.callToolUnpack(map);
        responseMsg.setRetCode(result.get("retCode").toString());
        responseMsg.setMessage(result.get("msg").toString());
        return responseMsg;
    }

    /**
     * ------------------------------------------------------
     * end
     * ------------------------------------------------------
     */

    /**
     * ------------------------------------------------------
     * 工作包料箱取消接口
     * ------------------------------------------------------
     */
    @PostMapping("/toolKitCancel")
    public ResponseMsg<String> toolKitCancel(@RequestBody Map map) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String result = materialReceiptService.toolKitCancel(map);
        if (result.equals("200")) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("工作包取消成功！");
        } else {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("工作包取消失败！");
            responseMsg.setErrorDesc(result);
        }
        return responseMsg;
    }

    @PostMapping("/callToolKitCancle")
    /**
     * 工作包取消，叫箱接口
     */
    public ResponseMsg<HashMap> callToolKitCancle(@RequestBody HashMap map) {
        ResponseMsg<HashMap> responseMsg = new ResponseMsg<>();
        HashMap result = materialReceiptService.callToolKitCancle(map);
        return responseMsg;
    }
    /**
     * ------------------------------------------------------
     * end
     * ------------------------------------------------------
     */

    /**
     * ------------------------------------------------------
     * 工作包料箱替换接口
     * ------------------------------------------------------
     */
    @PostMapping("/toolKitReplace")
    public ResponseMsg<String> toolKitReplace(@RequestBody Map map) {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String result = materialReceiptService.toolKitReplace(map);
        if (result.equals("200")) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("替换成功！");
        } else {
            responseMsg.setRetCode("201");
            responseMsg.setErrorDesc("替换失败！");
        }
        return responseMsg;
    }
    /**
     * ------------------------------------------------------
     * end
     * ------------------------------------------------------
     */

    /**
     * 异常处理，手动方式驱动叫箱
     *
     * @return
     */
    @PostMapping("/exceptionHandling")
    public ResponseMsg<HashMap> exceptionHandling(@RequestBody HashMap map) {
        ResponseMsg<HashMap> responseMsg = new ResponseMsg<>();
        HashMap workBinParam = new HashMap();
        HashMap toolParam = new HashMap();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        //缓存箱子结束位置
        String workbinBit = msSslShelvesService.findStartCode(IP, "WORKBIN");
        //工作包结束位置
        String toolBit = msSslShelvesService.findStartCode(IP, "TOOL");


//        workBinParam.put("endCode","xyssj"+workbinBit);
//        workBinParam.put("func","sort");
//        HashMap workBinResult = createCommonLog.callWCSInterface(workBinParam);
//        toolParam.put("endCode","xyssj"+toolBit);
//        toolParam.put("func","sort");
//        HashMap toolResult = createCommonLog.callWCSInterface(toolParam);
//        HashMap result = new HashMap();
//        result.put("toolReturn",toolResult);
//        result.put("workBInReturn",workBinResult);
//        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    @PostMapping("queryReceiveGkLog")
    public List<HashMap> queryReceiveGkLog() {
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        return materialReceiptService.queryReceiveGkLog(IP);
    }

    //矫正缓存箱中物料数量
    @PostMapping("rightWorkbin")
    public HashMap rightWorkbin(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        HashMap dt = (HashMap) map.get("data");
        int retNum = msWorkbinMaterialDao.rightWorkbin(dt);
        //处理matchinfo表数据
        if (Integer.parseInt(dt.get("rightQty").toString()) == 0) {//纠正后物料数量为0.跟新配置表
            msWorkbinMaterialDao.clearMatchInfo(dt);
        }
        if (retNum == 0) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", "缓存箱数据矫正失败");
            return hashMap;
        }
        hashMap.put("retCode", "200");
        hashMap.put("retMsg", "缓存箱数据已矫正");
        return hashMap;
    }

    //查询缺件的工作包
    @PostMapping("lackPackage")
    public HashMap lackPackage(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        HashMap pageParameter = (HashMap) map.get("pageParameter");
        HashMap searchParams = (HashMap) map.get("searchParams");
        Integer pageNum = (Integer) pageParameter.get("page");
        Integer pageSize = (Integer) pageParameter.get("rows");
        PageHelper.startPage(pageNum, pageSize);
        List<HashMap> lackPackage = msWorkbinMaterialDao.lackPackage(searchParams);
        PageInfo pageInfo = new PageInfo(lackPackage);
        hashMap.put("retCode", "200");
        hashMap.put("retData", lackPackage);
        hashMap.put("totalCount", pageInfo.getTotal());
        hashMap.put("totalPage", pageInfo.getPages());
        return hashMap;
    }

    //查询可以进行替换的工作包
    @PostMapping("replanPackge")
    public HashMap replanPackge(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        HashMap pageParameter = (HashMap) map.get("pageParameter");
        HashMap searchParams = (HashMap) map.get("searchParams");
        Integer pageNum = (Integer) pageParameter.get("page");
        Integer pageSize = (Integer) pageParameter.get("rows");
        PageHelper.startPage(pageNum, pageSize);
        List<HashMap> replanPackge = materialReceiptUtil.comparePackAo(searchParams);
        PageInfo pageInfo = new PageInfo(replanPackge);
        hashMap.put("retCode", "200");
        hashMap.put("retData", replanPackge);
        hashMap.put("totalCount", pageInfo.getTotal());
        hashMap.put("totalPage", pageInfo.getPages());
        return hashMap;
    }

    //工作包替换
    @PostMapping("replacePackage")
    public ResponseMsg replacePackage(@RequestBody HashMap map) {

        return null;
    }

    //分拣保存补叫箱子查询可用箱子
    @PostMapping("usableWorkbinQuery")
    public HashMap usableWorkbinQuery(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        HashMap pageParameter = (HashMap) map.get("pageParameter");
        HashMap searchParams = (HashMap) map.get("searchParams");
        Integer pageNum = (Integer) pageParameter.get("pageNumber");
        Integer pageSize = (Integer) pageParameter.get("pageSize");
        PageHelper.startPage(pageNum, pageSize);
        List<HashMap> replanPackge = msWorkbinMaterialDao.usableWorkbinQuery(searchParams);
        PageInfo pageInfo = new PageInfo(replanPackge);
        hashMap.put("retCode", "200");
        hashMap.put("retData", replanPackge);
        hashMap.put("totalCount", pageInfo.getTotal());
        hashMap.put("totalPage", pageInfo.getPages());
        return hashMap;
    }

    /**
     * 查询工作包以及工作包AO,物料等相关信息
     **/
    @PostMapping("queryGzbMaterialTree")
    public HashMap queryGzbMaterialTree(@RequestBody HashMap map) {
        HashMap node = new HashMap();
        node.put("label", map.get("packageCode"));
        List<HashMap> aos = msWorkbinMaterialDao.queryAoCodeByPackage(map);

        for (HashMap ao : aos) {
            List<HashMap> bills = msWorkbinMaterialDao.queryBillByPackage(ao);
            ao.put("children", bills);
        }
        node.put("children", aos);
        return node;
    }

    //分拣保存补叫箱子创建新任务
    @PostMapping("reCallWorkbinTask")
    public HashMap reCallWorkbinTask(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        if (map.get("roadway") == null || "".equals(map.get("roadway"))) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", "选择箱子不存在巷道为空，请确认是否在货架上");
            return hashMap;
        }
        //1.判断该缓存箱是否能够创建任务
        //判断该缓存箱是否存在任务或在货架上
        int pCnt = msWorkbinMaterialDao.searchShelvesWorkbin((String) map.get("workbinCode"));
        if (pCnt == 0 && !"312080030000".equals(map.get("workbinCode"))) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", "托盘存在未完成任务或不在货架上");
            return hashMap;
        }
        //2.生成info表数据
        msWorkbinMaterialDao.reCallInfoTask(map);
        if ("312080030000".equals(map.get("workbinCode"))) {
            msWorkbinMaterialDao.insertBigPartGkLog(map);
            hashMap.put("retCode", "200");
            hashMap.put("retMsg", "大件补叫成功");
            return hashMap;
        }
        //3.调用创建任务方法
        //获得IP
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        //获取箱子开始位置
        HashMap tm = outStoreroomService.outStoreroomWorkbin(map);
        String startCode = tm.get("startCode").toString();

        //组装传入日志的参数
        map.put("palletCode", map.get("workbinCode"));
        map.put("startCode", startCode);
        map.put("taskType", "2");
        map.put("command", "1");
        map.put("boxType", "WORKBIN");
        map.put("IP", IP);
        map.put("callPriority", 0);
        map.put("result", "sort");
        map.put("func", "sort");
        map.put("isFinish", "N");
        //获取操作位置编号
        String operationBit = msSslShelvesService.findStartCode(map.get("IP").toString(), (String) map.get("boxType"));
        map.put("endCode", "xyssj" + operationBit);
        //创建日志
        HashMap s = createCommonLog.outBound(map);

        if (!s.get("retCode").equals("200")) {
            hashMap.put("retCode", s.get("retCode"));
            hashMap.put("retMsg", s.get("retMsg"));
            return hashMap;
        }
        //4.调用流量控制
        HashMap callRtrun = createCommonLog.callWCSInterface(map);
        if (!s.get("retCode").equals("200")) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", callRtrun.get("msg"));
            return hashMap;
        }
        hashMap.put("retCode", "200");
        hashMap.put("retMsg", "成功补叫缓存箱");
        return hashMap;
    }

    //分拣保存补叫托盘
    @PostMapping("reCalToolTask")
    public HashMap reCalToolTask() {
        HashMap hashMap = new HashMap();
        //1.查询能够进行出库的空托盘
        String palletCode = msWorkbinMaterialDao.callEmptyTool();
        if (palletCode == null) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", "货架暂无空托盘");
            return hashMap;
        }
        //2.调用创建任务方法
        //获得IP
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        HashMap m = new HashMap();
        m.put("workbinCode", palletCode);
        HashMap tm = outStoreroomService.outStoreroomWorkbin(m);
        String startCode = tm.get("startCode").toString();
        HashMap map = new HashMap();
        //组装传入日志的参数
        map.put("palletCode", palletCode);
        map.put("startCode", startCode);
        map.put("taskType", "2");
        map.put("command", "1");
        map.put("boxType", "TOOL");
        map.put("IP", IP);
        map.put("callPriority", 0);
        map.put("result", "sort");
        map.put("func", "sort");
        //获取操作位置编号
        String operationBit = msSslShelvesService.findStartCode(map.get("IP").toString(), (String) map.get("boxType"));
        map.put("endCode", "xyssj" + operationBit);
        //创建日志
        HashMap s = createCommonLog.outBound(map);
        if (!s.get("retCode").equals("200")) {
            hashMap.put("retCode", s.get("retCode"));
            hashMap.put("retMsg", s.get("retMsg"));
            return hashMap;
        }
        //3.调用流量控制
        HashMap callRtrun = createCommonLog.callWCSInterface(map);
        if (!s.get("retCode").equals("200")) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", callRtrun.get("msg"));
            return hashMap;
        }
        hashMap.put("retCode", "200");
        hashMap.put("retMsg", "成功补叫托盘");
        return hashMap;
    }

    /***************************
     * 工作包拆包
     * author:xiaojian
     *
     * ****************************************************/
    //工作包拆包查询分拣好并且缺件的工作包
    @PostMapping("/queryLackPackage")
    public HashMap queryLackPackage(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        HashMap pageParameter = (HashMap) map.get("pageParameter");
        HashMap searchParams = (HashMap) map.get("searchParams");
        Integer pageNum = (Integer) pageParameter.get("pageNum");
        Integer pageSize = (Integer) pageParameter.get("pageSize");
        PageHelper.startPage(pageNum, pageSize);
        //1.查询工作包父信息
        List<HashMap> queryLackPackages = msWorkbinMaterialDao.queryLackPackage(searchParams);

        //2.查询info 子信息
        for (HashMap queryLackPackage : queryLackPackages) {
            List<HashMap> lackPackageChildren = msWorkbinMaterialDao.queryPackageTool(queryLackPackage);
            queryLackPackage.put("children", lackPackageChildren);
            queryLackPackage.put("hasChildren", true);
        }
        PageInfo pageInfo = new PageInfo(queryLackPackages);
        hashMap.put("retCode", "200");
        hashMap.put("retData", queryLackPackages);
        hashMap.put("totalCount", pageInfo.getTotal());
        hashMap.put("totalPage", pageInfo.getPages());
        return hashMap;
    }

    //工作包拆包查询分拣好的工作包
    @PostMapping("/queryFullPackage")
    public HashMap queryFullPackage(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        HashMap pageParameter = (HashMap) map.get("pageParameter");
        HashMap searchParams = (HashMap) map.get("searchParams");
        Integer pageNum = (Integer) pageParameter.get("pageNum");
        Integer pageSize = (Integer) pageParameter.get("pageSize");
        PageHelper.startPage(pageNum, pageSize);
        //1.查询工作包中物料
        List<HashMap> queryFullPackages = msWorkbinMaterialDao.queryLackPackageChild(searchParams);

        //2.查询info 子信息
        for (HashMap queryFullPackage : queryFullPackages) {
            List<HashMap> fullPackageChildren = msWorkbinMaterialDao.fullPackageChild(queryFullPackage);
            queryFullPackage.put("children", fullPackageChildren);
        }
        PageInfo pageInfo = new PageInfo(queryFullPackages);
        hashMap.put("retCode", "200");
        hashMap.put("retData", queryFullPackages);
        hashMap.put("totalCount", pageInfo.getTotal());
        hashMap.put("totalPage", pageInfo.getPages());
        return hashMap;
    }

    //工作包拆包叫工作包托盘
    @PostMapping("/callPackageTool")
    @Transactional
    public HashMap callPackageTool(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        List<String> lackTools = new ArrayList<>();
        List<String> fullTools = new ArrayList<>();
        List<String> allToos = new ArrayList<>();
        //1.得到物料信息
        HashMap queryPackageMaterial = (HashMap) map.get("data");

        //2.查询所有缺少的物料所在托盘
        List<HashMap> lackToolCodes = msWorkbinMaterialDao.queryLackTool(queryPackageMaterial);
        if (lackToolCodes.size() == 0) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", "无法找到该物料所在托盘！");
            return hashMap;
        }
        for (HashMap lackToolCode : lackToolCodes) {
            //插入拆包临时表中
            lackToolCode.put("aoCode", queryPackageMaterial.get("aoCode"));
            lackToolCode.put("packageCode", queryPackageMaterial.get("packageCode"));
            lackToolCode.put("itemQty", queryPackageMaterial.get("itemQty"));
            lackToolCode.put("packageCount", queryPackageMaterial.get("packageCount"));

            lackToolCode.put("remark", 'L');
            msWorkbinMaterialDao.insertRemovePackage(lackToolCode);
            lackTools.add((String) lackToolCode.get("palletCode"));
            allToos.add((String) lackToolCode.get("palletCode"));
        }
        //3.查询需要进行拆包的工作包所在的托盘
        List<HashMap> fullToolCodes = msWorkbinMaterialDao.queryFullTool(queryPackageMaterial);
        if (lackToolCodes.size() == 0) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", "该物料不存在已经分拣完成的工作包进行拆包操作！");
            return hashMap;
        }

        for (HashMap fullToolCode : fullToolCodes) {
            //插入拆包临时表中
            fullToolCode.put("aoCode", queryPackageMaterial.get("aoCode"));
            fullToolCode.put("packageCode", queryPackageMaterial.get("packageCode"));
            fullToolCode.put("itemQty", queryPackageMaterial.get("itemQty"));
            fullToolCode.put("packageCount", queryPackageMaterial.get("packageCount"));
            fullToolCode.put("remark", 'F');
            msWorkbinMaterialDao.insertRemovePackage(fullToolCode);
            fullTools.add((String) fullToolCode.get("palletCode"));
            allToos.add((String) fullToolCode.get("palletCode"));
        }

        //下发托盘指令
        //4.获得IP
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        //5.判断当前位置所剩流量
        String toolLocation = msSslShelvesService.findStartCode(IP, "TOOL");
        String LocationTool = "xyssj" + toolLocation;
        int taskNumTool = msGkLogDao.searchCountNotBack(LocationTool);
        if (!Objects.isNull(toolLocation)) {
            if (toolLocation.equals("1146") || toolLocation.equals("1136") || toolLocation.equals("1126")
                    || toolLocation.equals("1116") || toolLocation.equals("1106")) {
                if (taskNumTool >= 6) {
                    hashMap.put("retCode", "201");
                    hashMap.put("retMsg", "当前位置可放托盘数量已满，请先回库再操作！");
                    return hashMap;
                }
            }
        }
        //6.判断货架状态
        for (int i = 0; i < allToos.size(); i++) {
            String palletCode = allToos.get(i);
            int ct = msSslShelvesService.searchPalletIsOnShelves(palletCode);
            if (ct == 0) {
                //判断托盘结束位是否是当前位置
                String endCode = msWorkbinMaterialDao.isFinishPosition(palletCode);
                if (endCode.equals(LocationTool)) {
                    continue;
                }
                hashMap.put("retCode", "201");
                hashMap.put("retMsg", "托盘" + palletCode + "当前位置为" + endCode + "，还未回库，请稍等，确认货架为占用状态再操作！");
                return hashMap;
            }
        }
        //7.下发缺少物料托盘任务
        for (String lackTool : lackTools) {
            HashMap logMap = new HashMap();
            //查询开始位置、巷道
            HashMap rowMap = msWorkbinMaterialDao.queryRowStatus(lackTool);
            if (rowMap != null) {
                logMap.put("startCode", rowMap.get("startCode"));
                logMap.put("roadway", rowMap.get("roadway"));
            } else {
                continue;
            }
            //组装传入日志的参数
            logMap.put("palletCode", lackTool);

            logMap.put("taskType", "2");
            logMap.put("command", "1");
            logMap.put("boxType", "TOOL");
            logMap.put("IP", IP);
            logMap.put("result", "lackRemove");
            //获取操作位置编号
            String operationBit = msSslShelvesService.findStartCode(logMap.get("IP").toString(), (String) logMap.get("boxType"));
            logMap.put("endCode", "xyssj" + operationBit);
            //创建日志
            HashMap s = createCommonLog.outBound(logMap);
        }
        //8.下发需要拆包物料托盘任务
        for (String fullTool : fullTools) {
            HashMap logMap = new HashMap();
            //查询开始位置、巷道
            HashMap rowMap = msWorkbinMaterialDao.queryRowStatus(fullTool);
            if (rowMap != null) {
                logMap.put("startCode", rowMap.get("startCode"));
                logMap.put("roadway", rowMap.get("roadway"));
            } else {
                continue;
            }
            //组装传入日志的参数
            logMap.put("palletCode", fullTool);
            logMap.put("taskType", "2");
            logMap.put("command", "1");
            logMap.put("boxType", "TOOL");
            logMap.put("IP", IP);
            logMap.put("result", "fullRemove");
            //获取操作位置编号
            String operationBit = msSslShelvesService.findStartCode(logMap.get("IP").toString(), (String) logMap.get("boxType"));
            logMap.put("endCode", "xyssj" + operationBit);
            //创建日志
            HashMap s = createCommonLog.outBound(logMap);
        }
        String operationBit = msSslShelvesService.findStartCode(IP, "TOOL");
        List<String> allTask = msWorkbinMaterialDao.queryWaitTask("xyssj" + operationBit, taskNumTool);
        //9.下发任务给wcs
        for (int i = 0; i < allTask.size(); i++) {
            String palletCode = allTask.get(i);
            HashMap outMap = new HashMap();
            //查询开始位置、巷道
            HashMap rowMap = msWorkbinMaterialDao.queryRowStatus(palletCode);
            if (rowMap != null) {
                outMap.put("startCode", rowMap.get("startCode"));
                outMap.put("roadway", rowMap.get("roadway"));
            } else {
                continue;
            }
            outMap.put("palletCode", palletCode);
            outMap.put("boxType", "TOOL");
            outMap.put("taskType", "2");
            outMap.put("command", "1");
            outMap.put("endCode", LocationTool);
            outMap.put("isBack", "N");
            msSslShelvesRest.doTask(outMap);
        }
        hashMap.put("retCode", "200");
        hashMap.put("retMsg", "托盘任务已下发！");
        return hashMap;
    }

    //工作包拆包叫托盘及缓存箱
    @PostMapping("/callPackageWorkbin")
    @Transactional
    public HashMap callPackageWorkbin(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        List<String> toolMaps = new ArrayList<>();
        List<String> workbinMaps = new ArrayList<>();
        //1.得到需要拆包的工作包所在托盘
        HashMap queryPackageMaterial = (HashMap) map.get("data");
        List<HashMap> fullToolCodes = msWorkbinMaterialDao.queryLackTool(queryPackageMaterial);
        for (HashMap fullToolCode : fullToolCodes) {
            fullToolCode.put("aoCode", queryPackageMaterial.get("aoCode"));
            fullToolCode.put("packageCode", queryPackageMaterial.get("packageCode"));
            fullToolCode.put("itemQty", queryPackageMaterial.get("itemQty"));
            fullToolCode.put("packageCount", queryPackageMaterial.get("packageCount"));
            fullToolCode.put("remark", 'F');
            msWorkbinMaterialDao.insertRemovePackage(fullToolCode);
            toolMaps.add((String) fullToolCode.get("palletCode"));
        }

        //2.找到缓存箱
        //查找规则表，计算需要多少个缓存箱
        Integer itemRuleQty = msWorkbinMaterialDao.queryItemRule(queryPackageMaterial);
        Integer needQty = (Integer) queryPackageMaterial.get("itemQty");
        List<HashMap> workbins = msWorkbinMaterialDao.queryWorkbin(queryPackageMaterial);
        if (workbins.size() == 0) {
            //查找货架上空箱
            Integer workbinQty = needQty / itemRuleQty;
            Integer delQty = needQty % itemRuleQty;
            if (delQty > 0) {
                workbinQty = workbinQty + 1;
                List<String> emptyWorkbins = msWorkbinMaterialDao.queryEmptyWorkbin(workbinQty);
                if (emptyWorkbins.size() == 0) {
                    hashMap.put("retCode", "201");
                    hashMap.put("retMsg", "货架上没有找到存放过该物料的缓存箱及空箱！");
                    return hashMap;
                }
                for (String emptyWorkbin : emptyWorkbins) {
                    workbinMaps.add(emptyWorkbin);
                }
                for (int i = 0; i < emptyWorkbins.size(); i++) {
                    String emptyWorkbin = emptyWorkbins.get(i);
                    HashMap lackWorkbinCode = new HashMap();
                    lackWorkbinCode.put("palletCode", emptyWorkbin);
                    lackWorkbinCode.put("qualityCode", queryPackageMaterial.get("qualityCode"));
                    lackWorkbinCode.put("itemCode", queryPackageMaterial.get("itemCode"));
                    lackWorkbinCode.put("aoCode", queryPackageMaterial.get("aoCode"));
                    lackWorkbinCode.put("packageCode", queryPackageMaterial.get("packageCode"));
                    if (i == emptyWorkbins.size() - 1) {
                        lackWorkbinCode.put("itemQty", delQty);
                    } else {
                        lackWorkbinCode.put("itemQty", itemRuleQty);
                    }
                    lackWorkbinCode.put("packageCount", queryPackageMaterial.get("packageCount"));
                    lackWorkbinCode.put("remark", 'L');
                    msWorkbinMaterialDao.insertRemovePackage(lackWorkbinCode);
                }
            } else {
                List<String> emptyWorkbins = msWorkbinMaterialDao.queryEmptyWorkbin(workbinQty);
                if (emptyWorkbins.size() == 0) {
                    hashMap.put("retCode", "201");
                    hashMap.put("retMsg", "货架上没有找到存放过该物料的缓存箱及空箱！");
                    return hashMap;
                }
                for (String emptyWorkbin : emptyWorkbins) {
                    HashMap lackWorkbinCode = new HashMap();
                    lackWorkbinCode.put("palletCode", emptyWorkbin);
                    lackWorkbinCode.put("qualityCode", queryPackageMaterial.get("qualityCode"));
                    lackWorkbinCode.put("itemCode", queryPackageMaterial.get("itemCode"));
                    lackWorkbinCode.put("aoCode", queryPackageMaterial.get("aoCode"));
                    lackWorkbinCode.put("packageCode", queryPackageMaterial.get("packageCode"));
                    lackWorkbinCode.put("itemQty", itemRuleQty);
                    lackWorkbinCode.put("packageCount", queryPackageMaterial.get("packageCount"));
                    lackWorkbinCode.put("remark", 'L');
                    msWorkbinMaterialDao.insertRemovePackage(lackWorkbinCode);
                    workbinMaps.add(emptyWorkbin);
                }
            }


        } else {
            for (HashMap workbin : workbins) {
                Integer itemQty = (Integer) workbin.get("itemQty");
                needQty = needQty - (itemRuleQty - itemQty);
                if (needQty <= 0) {
                    workbinMaps.add((String) workbin.get("workbinCode"));
                    HashMap lackWorkbinCode = new HashMap();
                    lackWorkbinCode.put("palletCode", workbin.get("workbinCode"));
                    lackWorkbinCode.put("qualityCode", queryPackageMaterial.get("qualityCode"));
                    lackWorkbinCode.put("itemCode", queryPackageMaterial.get("itemCode"));
                    lackWorkbinCode.put("aoCode", queryPackageMaterial.get("aoCode"));
                    lackWorkbinCode.put("packageCode", queryPackageMaterial.get("packageCode"));
                    lackWorkbinCode.put("itemQty", needQty);
                    lackWorkbinCode.put("packageCount", queryPackageMaterial.get("packageCount"));
                    lackWorkbinCode.put("remark", 'L');
                    msWorkbinMaterialDao.insertRemovePackage(lackWorkbinCode);
                    break;
                }
                HashMap lackWorkbinCode = new HashMap();
                lackWorkbinCode.put("palletCode", workbin.get("workbinCode"));
                lackWorkbinCode.put("qualityCode", queryPackageMaterial.get("qualityCode"));
                lackWorkbinCode.put("itemCode", queryPackageMaterial.get("itemCode"));
                lackWorkbinCode.put("aoCode", queryPackageMaterial.get("aoCode"));
                lackWorkbinCode.put("packageCode", queryPackageMaterial.get("packageCode"));
                lackWorkbinCode.put("itemQty", itemRuleQty - itemQty);
                lackWorkbinCode.put("packageCount", queryPackageMaterial.get("packageCount"));
                lackWorkbinCode.put("remark", 'L');
                msWorkbinMaterialDao.insertRemovePackage(lackWorkbinCode);
                workbinMaps.add((String) workbin.get("workbinCode"));
            }
        }
        //3.获得IP
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        //4.判断当前位置所剩流量
        String toolLocation = msSslShelvesService.findStartCode(IP, "TOOL");
        String workbinLocation = msSslShelvesService.findStartCode(IP, "TOOL");
        String LocationTool = "xyssj" + toolLocation;
        String LocationWorkbin = "xyssj" + workbinLocation;
        int taskNumTool = msGkLogDao.searchCountNotBack(LocationTool);
        int taskNumWorkbin = msGkLogDao.searchCountNotBack(LocationWorkbin);
        if (!Objects.isNull(toolLocation)) {
            if (toolLocation.equals("1146") || toolLocation.equals("1136") || toolLocation.equals("1126")
                    || toolLocation.equals("1116") || toolLocation.equals("1106")) {
                if (taskNumTool >= 6) {
                    hashMap.put("retCode", "201");
                    hashMap.put("retMsg", "当前位置可放托盘数量已满，请先回库再操作！");
                    return hashMap;
                }
            }
        }
        if (!Objects.isNull(workbinLocation)) {
            if (workbinLocation.equals("1150") || workbinLocation.equals("1140") || workbinLocation.equals("1130")
                    || workbinLocation.equals("1120") || workbinLocation.equals("1110")) {
                if (taskNumWorkbin >= 4) {
                    hashMap.put("retCode", "201");
                    hashMap.put("retMsg", "当前位置可放缓存箱数量已满，请先回库再操作！");
                    return hashMap;
                }
            }
        }
        //5.判断货架状态
        for (int i = 0; i < toolMaps.size(); i++) {
            String palletCode = toolMaps.get(i);
            int ct = msSslShelvesService.searchPalletIsOnShelves(palletCode);
            if (ct == 0) {
                //判断托盘结束位是否是当前位置
                String endCode = msWorkbinMaterialDao.isFinishPosition(palletCode);
                if (endCode.equals(LocationTool)) {
                    continue;
                }
                hashMap.put("retCode", "201");
                hashMap.put("retMsg", "托盘" + palletCode + "当前位置为" + endCode + "，还未回库，请稍等，确认货架为占用状态再操作！");
                return hashMap;
            }
        }
        //6.下发需要拆包物料托盘任务
        for (String toolMap : toolMaps) {
            HashMap logMap = new HashMap();
            //查询开始位置、巷道
            HashMap rowMap = msWorkbinMaterialDao.queryRowStatus(toolMap);
            if (rowMap != null) {
                logMap.put("startCode", rowMap.get("startCode"));
                logMap.put("roadway", rowMap.get("roadway"));
            } else {
                continue;
            }
            //组装传入日志的参数
            logMap.put("palletCode", toolMap);
            logMap.put("taskType", "2");
            logMap.put("command", "1");
            logMap.put("boxType", "TOOL");
            logMap.put("IP", IP);
            logMap.put("result", "fullRemove");
            //获取操作位置编号
            String operationBit = msSslShelvesService.findStartCode(logMap.get("IP").toString(), (String) logMap.get("boxType"));
            logMap.put("endCode", "xyssj" + operationBit);
            //创建日志
            HashMap s = createCommonLog.outBound(logMap);
        }
        //7.下发缓存箱任务
        for (String workbinMap : workbinMaps) {
            HashMap logMap = new HashMap();
            //查询开始位置、巷道
            HashMap rowMap = msWorkbinMaterialDao.queryRowStatus(workbinMap);
            if (rowMap != null) {
                logMap.put("startCode", rowMap.get("startCode"));
                logMap.put("roadway", rowMap.get("roadway"));
            } else {
                continue;
            }
            //组装传入日志的参数
            logMap.put("palletCode", workbinMap);

            logMap.put("taskType", "2");
            logMap.put("command", "1");
            logMap.put("boxType", "WORKBIN");
            logMap.put("IP", IP);
            logMap.put("result", "lackRemove");
            //获取操作位置编号
            String operationBit = msSslShelvesService.findStartCode(logMap.get("IP").toString(), (String) logMap.get("boxType"));
            logMap.put("endCode", "xyssj" + operationBit);
            //创建日志
            HashMap s = createCommonLog.outBound(logMap);
        }
        //8.下发任务给wcs
        String operationBitTool = msSslShelvesService.findStartCode(IP, "TOOL");
        String operationBitWorkbin = msSslShelvesService.findStartCode(IP, "TOOL");
        List<String> allToolTask = msWorkbinMaterialDao.queryWaitTask("xyssj" + operationBitTool, taskNumTool);
        List<String> allWorkbinTask = msWorkbinMaterialDao.queryWaitTask("xyssj" + operationBitWorkbin, taskNumTool);
        for (int i = 0; i < allToolTask.size(); i++) {
            String palletCode = allToolTask.get(i);
            HashMap outMap = new HashMap();
            //查询开始位置、巷道
            HashMap rowMap = msWorkbinMaterialDao.queryRowStatus(palletCode);
            if (rowMap != null) {
                outMap.put("startCode", rowMap.get("startCode"));
                outMap.put("roadway", rowMap.get("roadway"));
            } else {
                continue;
            }
            outMap.put("palletCode", palletCode);
            outMap.put("boxType", "TOOL");
            outMap.put("taskType", "2");
            outMap.put("command", "1");
            outMap.put("endCode", LocationTool);
            outMap.put("isBack", "N");
            msSslShelvesRest.doTask(outMap);
        }
        //8.下发任务给wcs
        for (int i = 0; i < allWorkbinTask.size(); i++) {
            String palletCode = allWorkbinTask.get(i);
            HashMap outMap = new HashMap();
            //查询开始位置、巷道
            HashMap rowMap = msWorkbinMaterialDao.queryRowStatus(palletCode);
            if (rowMap != null) {
                outMap.put("startCode", rowMap.get("startCode"));
                outMap.put("roadway", rowMap.get("roadway"));
            } else {
                continue;
            }
            outMap.put("palletCode", palletCode);
            outMap.put("boxType", "WORKBIN");
            outMap.put("taskType", "2");
            outMap.put("command", "1");
            outMap.put("endCode", LocationWorkbin);
            outMap.put("isBack", "N");
            msSslShelvesRest.doTask(outMap);
        }

        hashMap.put("retCode", "200");
        hashMap.put("retMsg", "托盘任务及缓存箱已下发！");
        return hashMap;
    }


    //进行托盘扫码
    @PostMapping("/scanPackageTool")
    public HashMap scanPackageTool(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();

        //返回物料信息
        HashMap scanMap = msWorkbinMaterialDao.queryRemoveMaterial(map);
        hashMap.put("retCode", "200");
        hashMap.put("retMsg", "托盘扫码成功！");
        hashMap.put("retData", scanMap);
        return hashMap;
    }

    //工作包拆包重新绑定关系
    @PostMapping("/rebindPackageTool")
    @Transactional
    public HashMap rebindPackageTool(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        //获得缺件物料信息
        HashMap LackMap = (HashMap) map.get("LACK");
        HashMap FullMap = (HashMap) map.get("FULL");
        //1.将进行拆包的工作包及AO改成缺件状态
        //查询缺件工作包状态，赋予拆包工作包
        String FullAState = msWorkbinMaterialDao.queryPackageState(LackMap);
        FullMap.put("state", "04");
        FullMap.put("aState", FullAState);
        msWorkbinMaterialDao.updateLackPackage(FullMap);
        msWorkbinMaterialDao.updateLackAo(FullMap);
        msWorkbinMaterialDao.updateFullInfo(FullMap);
        //更新托盘中物料数量
        msWorkbinMaterialDao.updateFullWorkbin(FullMap);

        //将当前物料表中数据配好
        msWorkbinMaterialDao.updateLackInfo(LackMap);
        //判断当前工作包是否物料已经配完
        Integer isPackageFinish = msWorkbinMaterialDao.isPackageFinish(LackMap);
        if (isPackageFinish == 0) {
            msWorkbinMaterialDao.updateLackPackage(LackMap);
            msWorkbinMaterialDao.updateLackAo(LackMap);
            msWorkbinMaterialDao.updateLackWorkbin(LackMap);
        }
        msWorkbinMaterialDao.updateRemove(LackMap);
        msWorkbinMaterialDao.updateRemove(FullMap);
        hashMap.put("retCode", "200");
        hashMap.put("retMsg", "拆包成功！");
        return hashMap;
    }

    //工作包拆包托盘缓存箱回库
    //参数：func    值：agv，表示配送agv；back，表示送回货架
    //参数：palletCode
    @PostMapping("/palletCodeBack")
    @Transactional
    public HashMap palletCodeBack(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String operationBit = null;
        String boxType = "TOOL";
        operationBit = msSslShelvesService.findStartCode(IP, boxType);
        //创建回库任务
        HashMap inMap = new HashMap();
        inMap.put("palletCode", map.get("palletCode"));
        String isAgvTool = msWorkbinMaterialDao.queryAgvTool(map);
        if (isAgvTool.equals("lackRemove")) {
            if (map.get("func").equals("agv")) {
                inMap.put("command", "6");
                inMap.put("taskType", "3");
                inMap.put("endCode", "agv");
            } else {
                inMap.put("command", "5");
            }
        } else {
            inMap.put("command", "5");
        }
        inMap.put("boxType", "TOOL");
        inMap.put("startCode", operationBit);
        //调用创建出库日志
        createCommonLog.inBound(inMap);
        HashMap backTask = msWorkbinMaterialDao.queryBackTask(inMap);
        if (backTask != null && !backTask.isEmpty()) {
            msSslShelvesRest.doTask(backTask);
            hashMap.put("retCode", "200");
            hashMap.put("retMsg", "拆包成功！");
        } else {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", "拆包失败！");
        }
        return hashMap;
    }

    //一键确认 验证密码
    @PostMapping("/confirmPassWord")
    public HashMap confirmPassWord(@RequestBody HashMap map) {
        HashMap hashMap = new HashMap();
        Integer isRight = msWorkbinMaterialDao.confirmPassWord(map);
        if (isRight != 1) {
            hashMap.put("retCode", "201");
            hashMap.put("retMsg", "密码错误，请重新输入密码！");
            return hashMap;
        }
        hashMap.put("retCode", "200");
        hashMap.put("retMsg", "密码正确！");
        return hashMap;
    }

    @PostMapping("queryPackageTools")
    public List<HashMap> queryPackageTools(@RequestBody HashMap map) {
        String packageCode = map.get("packageCode").toString();
        return msWorkbinMaterialDao.queryPackageTools(packageCode);
    }

    @PostMapping("updateRepair")
    public ResponseMsg updateRepair(@RequestBody HashMap param) {
        ResponseMsg responseMsg = new ResponseMsg();
        String workbinCode = (String) param.get("workbinCode");

        String rsl = materialReceiptUtil.repairMaterial(workbinCode);
        return responseMsg.setRetCode(rsl);
    }
}
